package com.softstao.guoyu.ui.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RelativeLayout;

import com.google.gson.Gson;
import com.igexin.sdk.PushManager;
import com.softstao.guoyu.R;
import com.softstao.guoyu.base.BaseActivity;
import com.softstao.guoyu.global.APIInterface;
import com.softstao.guoyu.global.AppManager;
import com.softstao.guoyu.global.SharePreferenceManager;
import com.softstao.guoyu.model.LoginInfo;
import com.softstao.guoyu.model.WechatLogin;
import com.softstao.guoyu.model.me.AgentId;
import com.softstao.guoyu.mvp.interactor.LoginInteractor;
import com.softstao.guoyu.mvp.presenter.LoginPresenter;
import com.softstao.guoyu.mvp.viewer.LoginViewer;
import com.softstao.guoyu.widget.HintDialog;
import com.softstao.softstaolibrary.library.utils.LZUtils;
import com.softstao.softstaolibrary.library.wechatpay.MD5Util;
import com.softstao.softstaolibrary.library.widget.LZToast;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.wangjie.androidinject.annotation.annotations.mvp.AIPresenter;

import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by vaikus on 2017/6/7.
 */

public class LoginActivity extends BaseActivity implements LoginViewer {

    @AIPresenter(presenter = LoginPresenter.class, interactor = LoginInteractor.class)
    LoginPresenter presenter;

    @BindView(R.id.username)
    EditText username;
    @BindView(R.id.password)
    EditText password;
    @BindView(R.id.loading)
    RelativeLayout loading;
    private UMShareAPI mShareAPI;
    private long waitTime = 2000;
    private long touchTime = 0;

    @Override
    public int _ContentView() {
        return R.layout.activity_login;
    }

    @Override
    public void initView() {
        initTitle("登录");
        titleBar.getDivider().setVisibility(View.GONE);
        titleBar.getLeftImageView().setVisibility(View.GONE);

        mShareAPI = UMShareAPI.get(this);
    }

    @OnClick({R.id.login_btn, R.id.register_btn, R.id.forget_psd, R.id.wechat})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.login_btn:
                if (!check()) {
                    return;
                }
                askLogin();
                break;
            case R.id.register_btn:
                Intent registerIntent = new Intent(context, WebViewActivity.class);
                registerIntent.putExtra("title","注册");
                registerIntent.putExtra("url", APIInterface.SERVER_WAP + "sign_up.html?inviteCode=1&referee=%E6%80%BB%E9%83%A8");
                startActivity(registerIntent);
                break;
            case R.id.forget_psd:
                startActivity(new Intent(context,ForgetPassActivity.class));
                break;
            case R.id.wechat:
                if (mShareAPI.isInstall(this, SHARE_MEDIA.WEIXIN)) {
                    SHARE_MEDIA platform = SHARE_MEDIA.WEIXIN;
                    SharePreferenceManager.getInstance().setOauthVerify(true);
                    UMAuthListener l = new UMAuthListener() {
                        @Override
                        public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                            Log.e("umeng", new Gson().toJson(map));
                            wechatLogin();
                        }

                        @Override
                        public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                            LZToast.getInstance(context).showToast("授权失败");
                        }

                        @Override
                        public void onCancel(SHARE_MEDIA share_media, int i) {
                            LZToast.getInstance(context).showToast("用户取消");
                        }
                    };
                    SharePreferenceManager.getInstance().setListener(l);
                    mShareAPI.doOauthVerify(this, platform, l);
                } else {
                    LZToast.getInstance(this).showToast("请先安装微信");
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mShareAPI.onActivityResult(requestCode, resultCode, data);
    }

    private boolean check() {
        if (TextUtils.isEmpty(username.getText())) {
            LZToast.getInstance(context).showToast("请输入账号");
            return false;
        }if (TextUtils.isEmpty(password.getText())) {
            LZToast.getInstance(context).showToast("请输入密码");
            return false;
        }
        return true;
    }

    @Override
    public void askLogin() {
        presenter.login(username.getText().toString(), MD5Util.MD5Encode(password.getText().toString(),null));
        loading.setVisibility(View.VISIBLE);
    }

    @Override
    public void wechatLogin() {
        if (TextUtils.isEmpty(SharePreferenceManager.getInstance().getWxCode())==false) {
            presenter.wechatLogin(SharePreferenceManager.getInstance().getWxCode());
            loading.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void loginResult(AgentId agentId) {
        SharePreferenceManager.getInstance().setLogin(true);
        SharePreferenceManager.getInstance().setAgentId(agentId.getAgentId());
        LoginInfo loginInfo = new LoginInfo();
        loginInfo.setUsername(username.getText().toString());
        loginInfo.setPassword(MD5Util.MD5Encode(password.getText().toString(),null));
        SharePreferenceManager.getInstance().setLoginInfo(loginInfo);
        loading.setVisibility(View.GONE);
        if (agentId.getIsImport()==0) {
            PushManager.getInstance().bindAlias(context,String.valueOf(SharePreferenceManager.getInstance().getAgentId()));
            startActivity(new Intent(context, MainActivity.class).putExtra("index", "4"));
            finish();
        }else {
            changePsd();
        }
    }

    @Override
    public void wechatResult(WechatLogin wechatLogin) {
        loading.setVisibility(View.GONE);
        if (wechatLogin!=null){
            if (TextUtils.isEmpty(wechatLogin.getOpenid())==false){
                SharePreferenceManager.getInstance().setOpen_id(wechatLogin.getOpenid());
                Log.e("login",wechatLogin.getOpenid());
            }
            if (wechatLogin.getAgentId()==0){
                LZToast.getInstance(context).showToast("您还未绑定账号");
                startActivity(new Intent(context,WechatBindingActivity.class));
            }else {
                SharePreferenceManager.getInstance().setLogin(true);
                SharePreferenceManager.getInstance().setAgentId(wechatLogin.getAgentId());
                PushManager.getInstance().bindAlias(context,String.valueOf(SharePreferenceManager.getInstance().getAgentId()));
                startActivity(new Intent(context, MainActivity.class).putExtra("index", "4"));
                finish();
            }
            SharePreferenceManager.getInstance().setListener(null);
        }
    }

    private void changePsd(){
        HintDialog dialog = new HintDialog(context,R.style.MyDialog);
        dialog.getWindow().setLayout(getScreenWidth()- LZUtils.dipToPix(context,55)*2, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setIcon(R.mipmap.hint_icon_alert);
        dialog.setTitle("重置密码");
        dialog.getCancelIc().setVisibility(View.GONE);
        dialog.setContentVisible();
        dialog.setContent("初始密码过于简单，请尽快修改密码。");
        dialog.setConfirm("去重置密码");
        dialog.getConfirm().setOnClickListener(v -> {
            dialog.dismiss();
            startActivity(new Intent(context,ForgetPassActivity.class));
        });
        dialog.show();
    }

    @Override
    protected void error(String msg) {
        super.error(msg);
        loading.setVisibility(View.GONE);
    }

    @Override
    public void onBackPressed() {
        long currentTime = System.currentTimeMillis();
        if ((currentTime - touchTime) >= waitTime) {
            LZToast.getInstance(this).showToast("再按一次退出" + getResources().getString(R.string.app_name));
            touchTime = currentTime;
        } else {
            AppManager.getAppManager().AppExit();
        }
    }
}
